#pragma once
#include "BaseApp.h"
#include "../resource.h"

class Starter : public BaseApp
{
public:
	Starter(InputEntry& input) : BaseApp(input)
	{
		ImageMatch::loadTargetImage(IDB_BITMAP1, &_M_img_launch);
	}

	~Starter()
	{
		delete _M_img_launch.pits;
	}

	StateCode launch(_WIN_DESC_ & window)
	{
		time_t start_tm, curr_tm;
		HWND hwnd;
		start_tm = clock();
		printf("[ATL]launch %ls by starter\n", window._M_TITLE);
		while (true)
		{
			curr_tm = clock();
			if ((curr_tm - start_tm) >= 120000)
			{
				return ERR_WINDOW_NOTFOUND;
			}
			hwnd = findWindow(window);
			if (hwnd)
			{
				printf("[ATL]found starter window!\n");
				return prepare(hwnd);
			}
			Sleep(1000);
		}
	}

	StateCode prepare(HWND& hwnd) override
	{
		ShowWindow(hwnd, SW_SHOW);
		SetForegroundWindow(hwnd);
		POINT pt;
		int retry = 0;
		while (retry ++ < 60)
		{
			if (g_mch->findTargetImg(_M_img_launch, pt, 0.000001))
			{
				RECT rect;
				if (!GetWindowRect(hwnd, &rect))
				{
					return ERR_GETRECT_FAIL;
				}
				_M_input->setCursorPosition(pt.x + 20, pt.y + 15);
				GetCursorPos(&pt);
				Sleep(50);
				_M_input->mouseClick();
				GetCursorPos(&pt);
				return ST_SUCCESS;
			}
			Sleep(1000);
		}
		return ERR_IMAGE_NOTFOUND;
	}

	StateCode input(HWND& hwnd) override
	{
		return ST_SUCCESS;
	}
private:
	_IMG_RAW_		_M_img_launch;
};
